var common = require("../../common/common.js");
var server = require("../../common/server.js");

//获取应用实例
const app = getApp()
// common.initTemplateInfo();
var pageIndex = 1;
var pageSize = 10;
Page({
  data: {
    coupon: '领优惠券',
    subcode: '扫码购物',
    order: '我的订单',
    pro_type: '商品分类',
    hot_sell: '畅销商品',
    logo: '../../resources/images/logo.png',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    searchLoading:false,
    hotSells: [],
    noData: false,
    pagination: false,
    animationData: {},//选择动画
    showModalStatus: false,//显示遮罩
    isenableaddcart: true,
    
    selectedInfo: "",//选中的规格信息
    selectStockInfo: '',//选中对应的库存信息
    crcode: "",//判断是否选中
    crname: "",//判断是否选中
    szcode: "",//判断是否选中
    szname: "",//判断是否选中

    brcode: "",//判断是否选中
    brname: "",//判断是否选中
    goodNum: 1,//商品数量
  },
  onLoad: function () {
    var that = this;
    that.initPageData();

    // 自动检查更新新版本小程序
    app.updateManager();
  },

  //以下为自定义点击事件
  onPullDownRefresh() {
    var that = this;
    //下拉  
    console.log("下拉");
    pageIndex = 1;

    that.setData({
      pagination: false
    });
    that.initPageData();
  },
  //以下为自定义点击事件
  onReachBottom: function () {
    var that = this;
    //上拉  
    console.log("上拉");
    pageIndex++;

    that.setData({
      pagination: true
    });
    that.initPageData();
  },
  initPageData: function () {
    var that = this;
    var currentCompany = app.globalData.currentCompany;
    var params = {
      companyid: currentCompany.companyid,
      shop_type: currentCompany.sp_shop_type,
      shop_code: currentCompany.sp_code,
      shop_upcode: currentCompany.sp_upcode,
      pageSize: pageSize,
      pageIndex: pageIndex,
      productname:that.data.productname ||''
    };

    that.setData({
      controller: '/api/wx/product/hot_sell',
      params: params
    })

    wx.showLoading({
      title: '加载中...',
      icon:'loading'
    })
    common.pagedDetails({
      that: that,
      succFun: function (data) {
        // console.log(JSON.stringify(data))
        if (data){
          that.setData({
            details: data
          })
        }
      },
      comFun:function(){
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
      
    })

    // server.postJSON(common.gb.CurrentURL + '/api/wx/product/hot_sell',
    //   {
    //     "companyid":currentCompany.companyid,
    //     "shop_type": currentCompany.sp_shop_type,
    //     "shop_code": currentCompany.sp_code,
    //     "shop_upcode": currentCompany.sp_upcode,
    //     "pageSize": pageSize,
    //     "pageIndex": pageIndex
    //   }, function (result) {
    //     console.log(result);
    //     var res = result.data;
    //     if (res.stat == 200) {
    //       var data = res.data;
          
    //       that.setData({
    //         hotSells: that.data.hotSells.concat(data),
    //         searchLoading:false
    //       })
    //     }
    //   });
  },
  toBuy: function (e) {
    wx.navigateTo({
      url: '../product/product'
    })
  },
  toCoupon: function (e) {
    wx.navigateTo({
      url: '../coupon/couponcenter'
    })
  },
  toOrder:function(e){
    wx.navigateTo({
      url: '../order/order-list/index?type=0'
    })
  },
  toDetail:function(e){
    var pd_code =  e.currentTarget.dataset.pdcode
    wx.navigateTo({
      url: '../product/product?pd_code=' + pd_code
    })
  },
  toScanCode: function(e){
    wx.scanCode({
      success: (res) => {
        console.log(res)
      }
    })
  },
  toType: function (e) {
    wx.navigateTo({
      url: '../classify/classify'
    })
    // wx.navigateTo({
    //   url: '../type/type'
    // })
  },
  /**选择花色 */
  chooseColor: function (data) {
    var that = this;
    var crcode = data.currentTarget.dataset.crcode;
    var crname = data.currentTarget.dataset.crname;
    var img = data.currentTarget.dataset.img;
    that.setData({//把选中值，放入判断值中
      crname: crname,
      crcode: crcode
    })

    that.setSelectData();

  },
  chooseSize: function (data) {
    var that = this;
    var szcode = data.currentTarget.dataset.szcode;
    var szname = data.currentTarget.dataset.szname;
    that.setData({//把选中值，放入判断值中
      szname: szname,
      szcode: szcode
    })

    that.setSelectData();

  },
  chooseBra: function (data) {
    var that = this;
    var brcode = data.currentTarget.dataset.brcode;
    var brname = data.currentTarget.dataset.brname;
    that.setData({//把选中值，放入判断值中
      brname: brname,
      brcode: brcode
    })

    that.setSelectData();

  },
  setSelectData: function () {
    var that = this;
    var select_sub_code = that.data.params.pd_code + '' + that.data.crcode + '' + that.data.szcode + '' + that.data.brcode;
    for (var i = 0; i < that.data.stock.length; i++) {
      var sd = that.data.stock[i];
      var sub_code = sd.sd_code;
      var sd_amount = sd.sd_amount;

      if (sub_code == select_sub_code) {
        if (sd_amount <= 0) {
          that.setData({
            goodNum: 0,
            sd_amount: 0,
            selectStockInfo: '库存不足',
            isenableaddcart: false
          })
        } else {
          that.setData({
            goodNum: 1,
            sd_amount: sd_amount,
            selectStockInfo: ' 库存：' + sd_amount,
            isenableaddcart: true
          })
        }
        break;
      }
    }
    var select_sub_name = that.data.crname + "-" + that.data.szname + "-" + that.data.brname;
    var laststr = select_sub_name.substring(select_sub_name.length-1);
    if (laststr=='-'){
      select_sub_name = select_sub_name.substring(0,select_sub_name.length - 1);
    }
    that.setData({
      select_sub_code: select_sub_code,
      select_sub_name: select_sub_name,
      selectedInfo: select_sub_name + " " + that.data.goodNum + "个"
    })
  },

  /**点击选择花色按钮、显示页面 */
  viewFlowerArea: function (data) {
    var that = this;

    //根据当前的商品获取对应的数据
    
    that.setData({
      controller: '/api/wx/product/load',
      params: {
        companyid: app.globalData.currentCompany.companyid,
        shop_code: app.globalData.currentCompany.sp_code,
        pd_code: data.currentTarget.dataset.pdcode
      }
    })

    common.doMethod({
      that: that,
      succFun: function (data) {
        var data = data.data;
        that.setData({
          imgs: data.imgs || [],
          product: data.product,
          color: data.color,
          size: data.size,
          stock: data.stock,
          bra: data.bra
        })
      }
    })
    var animation = wx.createAnimation({//动画
      duration: 500,//动画持续时间
      timingFunction: 'linear',//动画的效果 动画从头到尾的速度是相同的
    })
    animation.translateY(0).step()//在Y轴偏移tx，单位px
    this.animation = animation
    that.setData({
      showModalStatus: true,//显示遮罩       
      animationData: animation.export()
    })
    that.setData({//把选中值，放入判断值中
      isHidden: 1,
    })
  },
  /**隐藏选择花色区块 */
  hideModal: function (data) {
    var that = this;

    that.setData({
      crcode: '',
      szcode: '',
      brcode: '',
      crname: '',
      szname: '',
      brname: '',
      select_sub_code: '',
      select_sub_name: '',
      selectedInfo: ''
    })

    that.setData({//把选中值，放入判断值中
      showModalStatus: false,//显示遮罩       
      isHidden: 0,
    })
  },
  goodAdd: function (data) {
    var that = this;

    var goodCount = that.data.goodNum + 1;
    if (goodCount > that.data.sd_amount) {
      goodCount = that.data.goodNum;
    }
    that.setData({//商品数量+1
      goodNum: goodCount
    })

    that.setData({
      sytleSelect: that.data.crname + "-" + that.data.szname + " " + that.data.goodNum + "个"
    })
  },
  goodReduce: function (data) {
    var that = this;
    var goodCount = that.data.goodNum - 1;
    if (goodCount < 1) {
      goodCount = that.data.goodNum;
    }
    that.setData({//商品数量-1
      goodNum: goodCount
    })
    that.setData({
      sytleSelect: that.data.crname + "-" + that.data.szname + " " + that.data.goodNum + "个"
    })
  },
  /**
   * 加入购物车:关闭遮罩，提示加入成功
   */
  addCart: function (data) {
    var that = this;

    if (!that.data.select_sub_code) {
      wx.showToast({
        title: '您还没有选择规格~',
        icon: 'none'
      })
      return false;
    }

    if (!that.data.isenableaddcart) {
      wx.showToast({
        title: '选择的商品没有库存~',
        icon: 'none'
      })
      return false;
    }

    if (that.data.color.length > 0 && !that.data.crcode) {
      wx.showToast({
        title: '您还没有选择颜色~',
        icon: 'none'
      })
      return false;
    }
    if (that.data.size.length > 0 && !that.data.szcode) {
      wx.showToast({
        title: '您还没有选择尺码~',
        icon: 'none'
      })
      return false;
    }
    if (that.data.bra.length > 0 && !that.data.brcode) {
      wx.showToast({
        title: '您还没有选择杯型~',
        icon: 'none'
      })
      return false;
    }

    //抽取商品图片对应的名称
    var pd_pic = that.data.imgs[0].split(app.globalData.imgdir)[1];
    //直接跳转购物车
    that.setData({
      controller: '/api/wx/cart/addCart',
      params: {
        companyid: app.globalData.currentCompany.companyid,//公司id
        // shop_code: app.globalData.currentCompany.sp_code,//店铺编码
        pd_code: that.data.product.wp_pd_code,//商品编码
        wu_code: app.globalData.user.wu_code,//用户编码
        pd_name: that.data.product.wp_pd_name,//商品名称
        pd_pic: pd_pic,//商品主图
        cr_code: that.data.crcode,//颜色编码
        sz_code: that.data.szcode,//尺寸编码
        br_code: that.data.brcode,//杯型编码
        cr_name: that.data.crname,//颜色名称
        sz_name: that.data.szname,//尺寸名称
        br_name: that.data.brname,//杯型名称
        sub_code: that.data.select_sub_code,//选中的规格组合编码
        sub_name: that.data.select_sub_name,//选中的规格串 红色-XL-B
        amount: that.data.goodNum,//数量
        price: that.data.product.wp_rate_price,//价格      
        sell_price: that.data.product.wp_sell_price,//原价   
      }
    })

    common.doMethod({
      that: that,
      succFun: function (data) {
        wx.showToast({
          title: '成功加入购物车',
          icon: 'none',
          success: function () {
            that.hideModal();
          }
        })
      }
    })
  },

  bindinputget: function (e) {
    console.log(e);
    this.setData({
      productname: e.detail.value
    })

    this.bindSearch();
  },
  bindSearch: function (e) {
    var that = this;

    that.setData({
      details: [],
    });
    pageIndex = 1;
    that.initPageData()
  }
})
